import { useState } from "react";
import { Button, Input } from "antd";
export default function Bar() {
  const [list, setList] = useState([]);
  const [info, setInfo] = useState({});

  const increment = () => {
    if (info.id) {
      const newList = JSON.parse(JSON.stringify(list));
      const index = newList.findIndex((item) => item.id === info.id);
      newList[index].name = info.name;
      setList(newList);
    } else {
      setList([...list, { id: Date.now(), name: info.name }]);
    }
    setInfo({});
  };

  const decrement = (id) => setList(list.filter(item => item.id !== id));

  return (
    <>
      <span>
        <Input
          value={info.name}
          style={{ width: 300, marginRight: 10 }}
          onChange={(e) => setInfo({ ...info, name: e.target.value })}
        />
        <Button type="primary" onClick={() => increment()}>
          新增
        </Button>
      </span>
      <ul>
        {list?.map((item) => {
          return (
            <li
              key={item.id}
              style={{
                marginTop: 20,
                display: "flex",
                marginBottom: 10,
                alignItems: "center",
              }}
            >
              <div style={{ width: 200 }}>{item?.name}</div>
              <span>
                {" "}
                <Button
                  size="small"
                  type="primary"
                  style={{ marginRight: 10 }}
                  onClick={() => setInfo(item)}
                >
                  编辑
                </Button>
                <Button
                  size="small"
                  type="primary"
                  onClick={() => decrement(item?.id)}
                >
                  删除
                </Button>
              </span>
            </li>
          );
        })}
      </ul>
    </>
  );
}
